package cn.ytr.crm.util;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class CRMExceptionHandler {

    //针对所有的运行时期的异常
    @ExceptionHandler(RuntimeException.class)
    public String runtimeExceptionHandle(Exception ex, Model model) {
        //控制台输出异常信息
        ex.printStackTrace();
        System.out.println("Exception Message：" + ex.getMessage());

        model.addAttribute("ex", ex);
        return "common/error";
    }

    //针对无权限的异常
    @ExceptionHandler(UnauthorizedException.class)
    public ModelAndView unAuthorizedExceptionHandle(Exception ex, Model model, HandlerMethod method, HttpServletResponse response) throws IOException {
        //控制台输出异常信息
        //ex.printStackTrace();
        System.out.println("UnauthorizedException Message：" + ex.getMessage());

        //判断是否异步请求，如果是就返回 json 数据
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            JsonResult jsonResult = new JsonResult();
            jsonResult.mark("抱歉，你没有该权限~");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(jsonResult));
            return null;
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("common/nopermission");
            modelAndView.addObject("ex", ex);
            return modelAndView;
        }

    }


}

















































